package com.yidui.core.uikit.emoji.utils

import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import java.io.*


object FileUtils {
    /**
     * 读取对象
     */
    fun readObject(file: String?): Serializable? {
        var fis: FileInputStream? = null
        var ois: ObjectInputStream? = null
        try {
            fis = FileInputStream(file)
            ois = ObjectInputStream(fis)
            return ois.readObject() as Serializable
        } catch (ignored: FileNotFoundException) {
        } catch (e: Exception) {
            e.printStackTrace()
            //反序列化失败 - 删除缓存文件
            if (e is InvalidClassException) {
                val data = File(file)
                if (data.exists()) {
                    data.delete()
                }
            }
        } finally {
            try {
                ois?.close()
            } catch (ignored: Exception) {
            }
            try {
                fis?.close()
            } catch (ignored: Exception) {
            }
        }
        return null
    }


    /**
     * 保存对象
     */
    fun saveObject(ser: Serializable?, file: String?): Boolean {
        var fos: FileOutputStream? = null
        var oos: ObjectOutputStream? = null
        return try {
            fos = FileOutputStream(file)
            oos = ObjectOutputStream(fos)
            oos.writeObject(ser)
            oos.close()
            true
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            false
        } finally {
            try {
                oos?.close()
            } catch (ignored: java.lang.Exception) {
            }
            try {
                fos?.close()
            } catch (ignored: java.lang.Exception) {
            }
        }
    }

    @JvmStatic
    fun bitmapToDrawable(bitmap: Bitmap?): Drawable? {
        return BitmapDrawable(bitmap)
    }
}